package com.chen.springsecurity.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.chen.springsecurity.domain.LoginUser;
import com.chen.springsecurity.domain.ResponseResult;
import com.chen.springsecurity.domain.User;
import com.chen.springsecurity.service.LoginService;
import com.chen.springsecurity.utils.JwtUtil;
import com.chen.springsecurity.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author Y·C
 * @version 1.0.0
 * @ClassName LoginServiceImpl.java
 * @Description TODO
 * @createTime 2023年08月28日 16:44:00
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        //获取AuthenticationManager authenticate方法 进行用户的认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        // 获取认证后的用户信息
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证没有通过，给出对应的提示
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        //获取用户信息
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //获取用户id
        String userId = loginUser.getUser().getId().toString();
        //如果认证通过了，使用userId生成一个JWT token返回给前端
        //生成JWT token
        String jwt = JwtUtil.createJWT(userId);
        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);
        //把完成的用户信息存储到redis中，userId作为key
        redisCache.setCacheObject(userId,loginUser);
        return new ResponseResult(200,"登录成功",map);
    }

    @Override
    public ResponseResult logout() {
        //获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        //获取用户信息
        String s = JSONObject.toJSONString(authentication.getPrincipal());
        //转换为LoginUser对象
        LoginUser loginUser = JSONObject.parseObject(s, LoginUser.class);
        System.out.println("s = " + s);
        String userId = String.valueOf(loginUser.getUser().getId());
        //删除redis中的用户信息
        redisCache.deleteObject(userId);
        return new ResponseResult(200,"退出成功");
    }
}
